package com.zhao.util;

import lombok.extern.slf4j.Slf4j;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.StringReader;

/**
 * @Author:zhao
 * @Date: 2018/8/1 14:20
 * @Description: xml转对象工具
 */
@Slf4j
@SuppressWarnings("all")
public class BeanConverterUtil {

    private BeanConverterUtil(){
    }

    /**
     * 功能描述: 根据源xml数据字符串转目标实体对象
     *
     * @param target 目标实体
     * @param source 源XML字符串
     * @return
     * @auther zhao
     * @date 2018/8/1 14:22
     */
    public static <T> T converter(Class<T> target, String source) {
        try {
            JAXBContext context = JAXBContext.newInstance(target);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            SAXParserFactory sax = SAXParserFactory.newInstance();
            sax.setNamespaceAware(false);
            XMLReader reader = sax.newSAXParser().getXMLReader();
            Source saxSource = new SAXSource(reader, new InputSource(new StringReader(source)));
            T entity = target.newInstance();
            entity = (T) unmarshaller.unmarshal(saxSource);
            return entity;
        } catch (Exception e) {
            log.error("XML转Bean失败:{}", e);
        }
        return null;
    }

}
